package com.sjtu.rental.controller;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.sjtu.rental.entity.UserInfo;
import com.sjtu.rental.form.LoginForm;
import com.sjtu.rental.services.UserService;

/**
 * 登录
 * 
 * @author Jessdy
 * 
 */
@Controller
@RequestMapping("/login")
public class LoginController {

	@Autowired
	private Validator loginForm;

	@Autowired
	private UserService userService;
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.setValidator(this.loginForm);
	}

	/**
	 * 跳转到登录页面
	 * 
	 * @return 登录页面
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String init(Model model) {
		LoginForm form = new LoginForm();
		form.getUser().setUiUsername("用户名或邮箱地址");
		model.addAttribute("form", form);
		return "login";
	}

	/**
	 * 
	 * 登录检验
	 * 
	 * @param user
	 *            需要登录的用户
	 * @param br
	 *            登录错误的提示
	 * @param session
	 *            会话集合
	 * @return 首页
	 */
	@RequestMapping(method = RequestMethod.POST)
	public String login(@Valid @ModelAttribute("form") LoginForm loginForm,
			BindingResult br, HttpSession session) {
		if (br.hasErrors()) {
			return "login";
		} else {
			try {
				UserInfo user = userService.login(loginForm.getUser());
				if (user == null) {
					throw new RuntimeException("error user");
				}
				session.setAttribute("user", user);
			} catch (Exception e) {
				br.rejectValue("user.uiUsername", "login.error");
				return "login";
			}

			return "redirect:/";
		}
	}
}
